package com.supersoul.myself.controller;

import com.alibaba.fastjson.JSONObject;
import com.supersoul.myself.cache.TokenCache;
import com.supersoul.myself.entity.Category;
import com.supersoul.myself.entity.User;
import com.supersoul.myself.ex.ServiceException;
import com.supersoul.myself.service.CategoryService;
import com.supersoul.myself.util.PageVO;
import com.supersoul.myself.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping("/save")
    public R saveCategory(@RequestBody @Valid Category category, HttpServletRequest request) throws ServiceException {
        String token = request.getHeader("token");
        String tokenJson = stringRedisTemplate.opsForValue().get(token);
        User user = JSONObject.parseObject(tokenJson, User.class);
        String cgId = categoryService.saveCategory(category, user);
        return R.success(cgId);
    }

    @GetMapping("/delete/{id}")
    public R delCategoryById(@PathVariable("id") @NotEmpty String id) throws ServiceException {
        categoryService.delCategoryById(id);
        return R.success();
    }

    @GetMapping("/detail/{id}")
    public R getCategory(@PathVariable("id") @NotEmpty String id) throws ServiceException  {
        Category category = categoryService.getCategory(id);
        return R.success(category);
    }


    @GetMapping("/person/list")
    public R getCategoryAll(PageVO pageVO, HttpServletRequest request) throws ServiceException  {
        String token = request.getHeader("token");
        String tokenJson = stringRedisTemplate.opsForValue().get(token);
        User user = JSONObject.parseObject(tokenJson, User.class);
        Page<Category> categoryPage = categoryService.getCategoryByUser(pageVO, user);
        return R.success(categoryPage);
    }

}
